<template>
  <div class="containers">
    <div class="topSearch card-search">
      <el-form :inline="true" :model="formInline" key="1" class="demo-form-inline">
        <el-form-item label="石墨棒编号">
          <el-input size="small" v-model="formInline.name"></el-input>
        </el-form-item>
        <!-- <el-form-item label="工艺状态">
          <el-select size="small" v-model="formInline.types" clearable>
            <el-option
              v-for="item in optionProcess"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="产品状态">
          <el-select size="small" v-model="formInline.productStatus">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formInline.productStatus === '已质检'" label="正废品">
          <el-select size="small" v-model="formInline.positiveWaste" clearable>
            <el-option
              v-for="item in options2"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getQualityData">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
      <tableQuality :tabledata="this.TABLEdata" :needEdit="editing">
        <el-table-column
          slot="densitys"
          label="密度-g/cｍ³"
          align="center">
          <template slot-scope="scope">
            <div>{{scope.row.density}}</div>
          </template>
        </el-table-column>
        <el-table-column
          slot="status"
          label="产品状态"
          align="center">
          <template slot-scope="scope">
            <el-tag size="medium" :type="scope.row.productStatus === '已质检' ? 'success' : 'danger'">{{scope.row.productStatus}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          slot="checkMans"
          label="工单质检人"
          width="80"
          align="center">
          <template slot-scope="scope">
            <div>{{scope.row.checkMan}}</div>
          </template>
        </el-table-column>
        <el-table-column
          slot="operation"
          label="操作"
          align="center"
          width="120">
          <template slot-scope="scope">
            <div class="btns" style="display: flex; margin-left: 10px">
              <el-button v-if="!scope.row.saveOrEdit" :disabled="scope.row.saveOrEdit" class="btnStyle" type="primary" @click="editRow(scope.row)">编辑</el-button>
              <el-button v-else class="btnStyle" type="danger" @click="cancels(scope.row)">取消</el-button>
              <el-button :disabled="!scope.row.saveOrEdit" class="btnStyle" type="success" @click="saveForm(scope.row)">保存</el-button>
            </div>
          </template>
        </el-table-column>
      </tableQuality>
      <div
        class="block"
        style="display: flex; flex-direction: row-reverse; margin-top: 10px; padding-right: 10px"
      >
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currPage"
          :page-sizes="[10, 20, 30]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
  </div>
</template>

<script>
// import '@/mock/dataCenter.js'
import { profileQualityUpdate, profileQualityData } from '@/api/profileApi/profileOrder.js'
import tableQuality from '@/components/tableQuality/index.vue'
import { mapGetters } from 'vuex'
export default {
  name: 'profileQuality',
  components: {
    tableQuality
  },
  data () {
    return {
      TABLEdata: {
        formHead: [],
        formHeadComplex: [],
        tableAllData: []
      },
      formInline: {
        name: '',
        productStatus: '全部',
        positiveWaste: '' // 正废品
      },
      ruleForm: {},
      options: [
        {
          label: '待质检',
          value: '待质检'
        },
        {
          label: '已质检',
          value: '已质检'
        },
        {
          label: '全部',
          value: '全部'
        }
      ], // 调获取规格类型接口
      options2: [
        {
          value: '正品',
          label: '正品'
        },
        {
          value: '废品',
          label: '废品'
        }
      ],
      saveOrEdit: false,
      pageSize: 10,
      currPage: 1,
      total: 50,
      editGroup: [],
      editing: [],
      itemForm: null
    }
  },
  props: {
  },
  computed: {
    ...mapGetters({
      getUserInfos: 'getUserInfo'
    })
  },
  created () {
    this.getQualityData()
  },
  mounted () {
  },
  beforeRouteLeave (to, from, next) {
    if (this.editing.length > 0) {
      this.$message({
        message: '有编辑好的没有保存',
        type: 'warning'
      })
    } else {
      next()
    }
  },
  methods: {
    editRow (row) {
      console.log('点击编辑', row)
      row.hightLight = true
      if (row.isCertified === '废品') {
        row.isdisabled = true
        row.numNotNeedUpdate = true
      }
      this.ruleForm = row
      this.ruleForm.saveOrEdit = true
      this.editing.push({ // 多个要编辑
        booleanss: true,
        rows: row._id,
        rowItemPass: JSON.parse(JSON.stringify(row)) // 点击编辑的时候保存最初状态
      })
      if (row.isCertified === '废品') { // 默认填充
        row.isCertified = '废品'
      } else {
        row.isCertified = '正品'
      }
    },
    copyApart (old, news) {
      for (var k in news) {
        old[k] = news[k]
      }
    },
    cancels (row) {
      var cancelRowitem = this.editing.filter(item => { return item.rows === row._id })
      this.copyApart(row, cancelRowitem[0].rowItemPass)
      row.isdisabled = false
      row.saveOrEdit = false
      row.hightLight = false
      this.editing.splice(this.findIndex(this.editing, row._id), 1)
    },
    // 计算 体积 密度
    computeDensityAndV (row) {
      if (row.productType !== '方子') {
        row.height = parseFloat(row.height)
        row.diameter = parseFloat(row.diameter)
        row.weight = parseFloat(row.weight)
        row.volume = Math.PI * row.height * 0.001 * (row.diameter / 2) * (row.diameter / 2)
        // row.volume = Math.floor(row.volume * 100) / 100 // 向下取整保留两位
        row.density = Math.floor(row.weight * 1000 / row.volume * 100) / 100
        row.height = row.height.toString()
        row.diameter = row.diameter.toString()
        row.weight = row.weight.toString()
        row.volume = row.volume.toString()
        row.density = row.density.toString()
      } else {
        row.heightSquare = parseFloat(row.heightSquare)
        row.weight = parseFloat(row.weight)
        row.length = parseFloat(row.length)
        row.width = parseFloat(row.width)
        row.volume = row.length * row.width * row.heightSquare
        row.density = Math.floor(row.weight * 1000 / row.volume * 100) / 100
        row.heightSquare = row.heightSquare.toString()
        row.length = row.length.toString()
        row.width = row.width.toString()
        row.weight = row.weight.toString()
        row.volume = row.volume.toString()
        row.density = row.density.toString()
      }
    },
    findIndex (arr, item) {
      for (let index = 0; index < arr.length; index++) {
        if (arr[index].rows === item) {
          return index
        }
      }
    },
    saveForm (row) {
      console.log('保存的这一行 修改这一行', row, row._id)
      if ((row.height !== '-' && row.weight !== '-' && row.diameter !== '-') || (row.heightSquare !== '-' && row.weight !== '-' && row.length !== '-' && row.width !== '-')) {
        row.numNotNeedUpdate = false
        this.computeDensityAndV(row)
        row.saveOrEdit = false
        this.editing.splice(this.findIndex(this.editing, row._id), 1)
        this.itemForm = JSON.parse(JSON.stringify(row))
        delete this.itemForm.saveOrEdit
        this.itemForm.checkMan = this.getUserInfos.account
        this.itemForm.createTime = this.itemForm.completeCreateTime
        console.log('this.itemForm', this.itemForm)
        profileQualityUpdate(this.itemForm).then(res => {
          console.log('编辑成功没', res)
          if (res.data.code === 200) {
            row.hightLight = false
            this.getQualityData()
            this.$message({
              showClose: true,
              message: '编辑成功',
              type: 'success'
            })
          }
        })
      } else {
        if (row.numNotNeedUpdate === true) {
          // 废品状态
          row.saveOrEdit = false
          const rowCopy = JSON.parse(JSON.stringify(row))
          delete rowCopy.saveOrEdit
          delete rowCopy.numNotNeedUpdate
          rowCopy.checkMan = this.getUserInfos.account
          rowCopy.createTime = rowCopy.completeCreateTime
          console.log('tthis.rowCopy', rowCopy)
          profileQualityUpdate(rowCopy).then(res => {
            console.log('编辑废品 不传长宽', res)
            this.editing.splice(this.findIndex(this.editing, row._id), 1)
            if (res.data.code === 200) {
              row.hightLight = false
              this.getQualityData()
              this.$message({
                showClose: true,
                message: '编辑成功',
                type: 'success'
              })
            }
          })
        } else { // 每一项包含0的情况
          row.saveOrEdit = true
          this.$message.error('每一项都需填写')
        }
      }
    },
    getQualityData () {
      const params = {
        rodNumber: this.formInline.name,
        productStatus: this.formInline.productStatus, // 产品状态
        pageSize: this.pageSize,
        isCertified: this.formInline.productStatus === '已质检' ? this.formInline.positiveWaste : '', // 正废品
        // status: '成型', // 工艺状态 写死
        currPage: this.currPage
      }
      profileQualityData(params).then(res => {
        if (res.data.code === 200) {
          console.log('成型质检', res.data.data)
          var oneLevel = JSON.parse(JSON.stringify(res.data.data.formHead))
          delete oneLevel.circularColumn
          delete oneLevel.square
          delete oneLevel.density
          var arr = []
          for (var i in oneLevel) {
            var o = {}
            o[i] = oneLevel[i]
            arr.push(o)
          }
          this.total = res.data.data.totalCount
          this.TABLEdata.formHead = arr
          const moreLevel = [
            {
              name: 'circularColumn',
              translate: '石墨电极和接头',
              children: [
                {
                  name: 'diameter',
                  translate: '直径/mm'
                },
                {
                  name: 'height',
                  translate: '高度/mm'
                }
              ]
            },
            {
              name: 'square',
              translate: '方子',
              children: [
                {
                  name: 'heightSquare',
                  translate: '高度/mm'
                },
                {
                  name: 'length',
                  translate: '长度/mm'
                },
                {
                  name: 'width',
                  translate: '宽度/mm'
                }
              ]
            }
          ]
          this.TABLEdata.formHeadComplex = moreLevel
          var tableBody = JSON.parse(JSON.stringify(res.data.data.data))
          tableBody.forEach((item) => {
            item.completeCreateTime = item.createTime
            if (item.createTime.length === 19) {
              item.createTime = item.createTime.substring(5, 16)
            }
          })
          if (this.editing.length !== 0) {
            this.editing.forEach((item) => { // 将还有没编辑的还原状态
              tableBody.forEach(i => {
                if (item.rows === i._id) {
                  i.saveOrEdit = true
                }
              })
            })
          }
          this.TABLEdata.tableAllData = tableBody
        }
      })
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.getQualityData()
    },
    handleCurrentChange (val) {
      this.currPage = val
      this.getQualityData()
    }
  }
}
</script>

